package com.gome.gop.mybatis.rw.datasource;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gome.gop.mybatis.DynamicDataSource;

public class DynamicDataSourceMethodInterceptor implements MethodInterceptor {
    
    private static Logger logger = LoggerFactory.getLogger(DynamicDataSourceMethodInterceptor.class);
    
    @Override
    public Object invoke(MethodInvocation invocation)
        throws Throwable {
        DynamicDataSource dynamicDataSource = invocation.getMethod().getAnnotation(DynamicDataSource.class);
        if (dynamicDataSource == null) {
            dynamicDataSource = invocation.getMethod().getDeclaringClass().getAnnotation(DynamicDataSource.class);
        }
        if (dynamicDataSource != null) {
            String dataSourceName = null;
            if (dynamicDataSource.name() != null && !"".equals(dynamicDataSource.name())) {
                dataSourceName = dynamicDataSource.name();
                logger.debug("方法已指定数据源名称:{}", dynamicDataSource.name());
            }
            else if (dynamicDataSource.value() != null && !"".equals(dynamicDataSource.value())) {
                dataSourceName = dynamicDataSource.value();
            }
            DynamicDataSourceHolder.setDataSource(dataSourceName);
        }
        Object obj = null;
        try {
            obj = invocation.proceed();
        }
        finally {
            logger.debug("清空指定的数据源");
            DynamicDataSourceHolder.clearDataSource();
        }
        
        return obj;
        
    }
    
}
